package chapter_3.server;

import chapter_3.VoteService;
import chapter_3.message.coder.MessageCoder;
import chapter_3.message.coder.TextMessageCoder;
import chapter_3.message.entity.RequestMessage;
import chapter_3.message.entity.ResponseMessage;
import org.w3c.dom.Text;

import javax.xml.crypto.Data;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Arrays;

public class VoteUDPServer {
    public static void main(String[] args) throws SocketException {
        int port = 9090;
        DatagramSocket socket = new DatagramSocket(port);
        byte[] receiveBuffer = new byte[TextMessageCoder.MESSAGE_MAX_LENGTH];
        MessageCoder msgCoder = new TextMessageCoder();
        VoteService voteService = new VoteService();

        //开始侦听消息
        while(true){
            System.out.println("--------------------开始监听消息--------------------");
            DatagramPacket packet = new DatagramPacket(receiveBuffer,receiveBuffer.length);
            try {
                socket.receive(packet);
                byte[] recvMsgBytes = Arrays.copyOfRange(packet.getData(), 0, packet.getLength());
                RequestMessage requestMessage = (RequestMessage) msgCoder.fromWire(recvMsgBytes);
                System.out.println("接收到来自: "+packet.getAddress().toString()+(requestMessage.getInquiryFlag()?"查询请求":"投票请求"));
                System.out.println("请求的候选人为: "+requestMessage.getCandidateId());
                ResponseMessage responseMessage = voteService.handleRequest(requestMessage);
                byte[] responseMsgBytes = msgCoder.toWire(responseMessage);
                packet.setData(responseMsgBytes);
                System.out.println("---------------发送返回消息--------------");
                socket.send(packet);
            }catch(IOException e){
                System.out.println("parse requestMessage error: "+e.getMessage());
            }
            System.out.println("消息发送成功");
        }
    }
}
